<template>
  <div>
    <n-card :bordered="false" title="用户管理" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :data="dataRef"
        :actionColumn="actionColumn"
        @edit-end="editEnd"
        @edit-row-end="editRowEnd"
        @edit-change="onEditChange"
        @update:checked-row-keys="onCheckedRow"
        striped
      >
        <template #tableTitle>
          <n-button type="primary" @click="addUserRef">
            <template #icon>
              <n-icon>
                <PlusOutlined/>
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>

        <template #action>
          <TableAction/>
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showPasswordModal" :show-icon="false" preset="dialog" title="重置密码">

      <n-form
        :model="pwdFormParams"
        :rules="pwdRules"
        ref="pwdFormRef"
        label-placement="left"
        :label-width="60"
        class="py-4"
      >
        <n-form-item label="密码" path="password">
          <n-input placeholder="请输入密码" type="password" show-password-on="click"
                   v-model:value="pwdFormParams.password"/>

          <n-button style="margin-left: 12px" @click="randomPasswd(16)">
            随机密码
          </n-button>
        </n-form-item>

      </n-form>

      <template #action>
        <n-space>
          <n-button @click="hidePasswordModal">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmPassword">重置</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal v-model:show="showUserModal" :show-icon="false" preset="dialog" title="增加用户">
      <n-form
        :model="userFormParams"
        :rules="userRules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="用户名" path="name">
          <n-input placeholder="请输入用户名" :allow-input="testName" v-model:value="userFormParams.name"/>
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input placeholder="请输入密码" type="password"
                   v-model:value="userFormParams.password"/>
        </n-form-item>
        <n-form-item label="确认密码" path="confirmPassword">
          <n-input placeholder="请输入确认密码" type="password"
                   v-model:value="userFormParams.confirmPassword"/>
        </n-form-item>
        <n-form-item label="姓名" path="realName">
          <n-input placeholder="请输入姓名" v-model:value="userFormParams.realName"/>
        </n-form-item>
        <n-form-item label="用户角色" path="manager">
          <n-select
            placeholder="请选择角色"
            v-model:value="userFormParams.manager"
            size="small"
            :options="roles"
          />
        </n-form-item>
        <n-form-item label="角色描述" path="desc">
          <n-input placeholder="请输入角色描述" v-model:value="userFormParams.desc"/>
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="cancelForm">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import {h, onMounted, reactive, ref, unref} from 'vue'
import {
  useMessage,
  useDialog, FormRules, NIcon
} from 'naive-ui'
import {useRouter} from "vue-router";
import {TableAction, BasicTable, BasicColumn} from "@/components/Table";
import {getTreeAll} from "@/utils";
import {PlusOutlined} from '@vicons/antd';
import {getUserList, sysUserDel, sysUserUpdate, sysUserAdd} from "@/api/system/user";
import {columns} from './columns';
import {useUserStore} from "@/store/modules/user";
import {SearchOutline} from "@vicons/ionicons5";
import {HmacSHA512} from "@/utils/crypto";

const router = useRouter();
const formRef: any = ref(null);
const pwdFormRef: any = ref(null);
const useMsg = useMessage();
const actionRef = ref();
const userStore = useUserStore();
const dialog = useDialog()

const showPasswordModal = ref(false);
const showUserModal = ref(false);
const formBtnLoading = ref(false);
const dataRef = ref([] as any)

const params = reactive({
  pageSize: 10,
  page: 1
});

const userFormParams = reactive({
  name: '',
  password: '',
  confirmPassword: '',
  realName: '',
  manager: null,
  desc: null,
});

const pwdFormParams = reactive({
  name: '',
  password: ''
})

const pwdRules: FormRules = {
  password: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入密码',
    min: 6,
    max: 36
  },
}

const userRules: FormRules = {
  name: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入用户名',
    },
    {
      validator: (rule, value: string) => {
        if (value != null) {
          return value.search(/^[a-zA-Z][a-zA-Z0-9_]*$/) != -1;
        }
        return true;
      },
      message: '用户只支持英文头和数字',
      trigger: ['blur', 'input'],
    }],
  password: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入密码',
    min: 6,
    max: 36
  },
  confirmPassword: [
    {
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      validator: (rule, value) => {
        if (userFormParams.password != null) {
          return (!!userFormParams.password &&
            userFormParams.password.startsWith(value) &&
            userFormParams.password.length >= value.length);
        }
        return true;

      },
      message: '两次输入密码不一致',
      trigger: 'input'
    },
    {
      validator: (rule, value) => {
        return value === userFormParams.password;
      },
      message: '两次输入密码不一致!',
      trigger: ['blur', 'password-input']
    }
  ],
  realName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入姓名',
  },
  manager: {
    type: 'boolean',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择平台',
  },
  desc: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入角色描述',
  },
};

const roles: any[] = [
  {
    label: '普通用户',
    value: false,
    disabled: false,
  },
  {
    label: '管理员',
    value: true,
    disabled: false,
  },
];

const actionColumn = reactive<BasicColumn>({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        ...createActions(record),
        {
          label: '删除',
          icon: 'ic:outline-delete-outline',
          onClick: () => {
            dialog.warning({
              title: '警告',
              content: `你确定删除用户:${record['name']}?`,
              positiveText: '确定',
              negativeText: '取消',
              onPositiveClick: () => {
                useMsg.info("handle delete")
                handleDelete(record)
              },
              onNegativeClick: () => {

              }
            })

          },
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return record['name'] != userStore.getUserId;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['basic_list'],
        },
      ],
    });
  },
});

function createActions(record) {
  if (!record.editable) {
    return [
      {
        label: '修改',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '重置密码',
        onClick: handleRest.bind(null, record),
      },
    ];
  } else {
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record),
      },
      {
        label: '取消',
        onClick: handleCancel.bind(null, record),
      },
    ];
  }
}

function testName(value){
  // return !value || /[@/'"#$%&、^*]+/.test(value);
  return !value || /^[a-zA-Z][a-zA-Z0-9_]*$/.test(value);
}
function addUserRef() {
  showUserModal.value = true;
}

const loadDataTable = async (res: any) => {
  let _params = {
    ...unref(params),
    ...res,
  };
  const table_data = await getUserList(_params);
  const {list} = table_data;
  dataRef.value = list;
  return table_data;
};

function onCheckedRow(rowKeys: any[]) {
  console.log("onCheckedRow", rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

function handleEdit(record) {
  record.onEdit?.(true);
}

// 重置密码
function handleRest(record) {
  pwdFormParams.name = record!.name;
  pwdFormParams.password = '';
  showPasswordModal.value = true;
}

function handleCancel(record) {
  record.onEdit?.(false, false);
}

async function handleSave(record) {
  const pass = await record.onEdit?.(false, true);
  if (pass) {
    const {message} = await sysUserUpdate({
      id: record.id,
      name: record.name,
      realName: record.realName,
      manager: record.manager,
      desc: record.desc,
    });
    useMsg.info(message);
    reloadTable();
  }
}

function onEditChange({column, value, record}) {
  // if (column.key === 'password') {
  //   // record.editValueRefs.name4.value = `${value}`;
  //   if (!!value) {
  //     column.editComponentProps.status = value.length < 6 ? 'error' : 'success';
  //     if (column.editRule == undefined)
  //       column.editRule = ((text, record) => {
  //         if (text.length < 6)
  //           return Promise.resolve("密码长度过短,必须大于6位");
  //       });
  //   } else {
  //     column.editComponentProps.status = null;
  //     unref(column.editRule);
  //     record['password'] = null;
  //   }
  // }
  // console.log("onEditChange", column, value, record);
}

function editRowEnd() {
  console.log("editRowEnd");
}

function editEnd({record, index, key, value}) {
  console.log("editEnd", index, key, record);
}

function cancelForm(e: any) {
  showUserModal.value = false;
}

function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const rsp = await sysUserAdd({
        name: userFormParams.name,
        realName: userFormParams.realName,
        manager: userFormParams.manager,
        desc: userFormParams.desc,
        password: HmacSHA512(userFormParams.confirmPassword),
      });
      useMsg.success('新增用户成功');
      setTimeout(() => {
        showUserModal.value = false;
        reloadTable();
      });
    } else {
      useMsg.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function hidePasswordModal(e: any) {
  showPasswordModal.value = false;
  pwdFormParams.password = '';
}

function randomPasswd(len = 10) {
  const RandomLower = () => {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 97)
  };
  const RandomUpper = () => {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 65)
  };
  const RandomNumber = () => {
    return String.fromCharCode(Math.floor(Math.random() * 10) + 48)
  };
  const CHARACTERS = '!@#$%^&*(){}[]=<>/,.~?-+_';
  const RandomCharacter = () => {
    return CHARACTERS[Math.floor(Math.random() * CHARACTERS.length)]
  };
  pwdFormParams.password = '';
  for (let i = 0; i < len; i++) {
    const j = Math.floor(Math.random() * 4);
    if (j == 0) {
      pwdFormParams.password += RandomLower();
    }
    if (j == 1) {
      pwdFormParams.password += RandomUpper();
    }
    if (j == 2) {
      pwdFormParams.password += RandomNumber();
    }
    if (j == 3) {
      pwdFormParams.password += RandomCharacter();
    }
  }
}

function confirmPassword(e: any) {
  formBtnLoading.value = true;
  pwdFormRef.value.validate(async (errors) => {
    if (!errors) {
      const rsp = await sysUserUpdate({
        name: pwdFormParams.name,
        password: pwdFormParams.password != null ? HmacSHA512(pwdFormParams.password) : null,
      });
      useMsg.success('密码修改成功');
      setTimeout(() => {
        showPasswordModal.value = false;
        useMsg.success('网络超时');
      });
    } else {
      useMsg.error('密码不能为空');
    }
    formBtnLoading.value = false;
  });
}

async function handleDelete(record: Recordable) {
  // console.log('点击了删除', record);
  await sysUserDel({username: record['name']});
  reloadTable();
  useMsg.info('用户已删除');
}


onMounted(async () => {
  // const {list,pageCount,page,pageSize} = await getUserList({});
  // expandedKeys.value = list.map((item) => item.key);
  // treeData.value = list;
});

</script>

<style lang="less" scoped></style>
